#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "GCursor.h"
#include "GWindow.h"
#include "../../Foundation/GUtilities/GError.h"

namespace GEngine
{
	bool GCursor::SetVisible(bool Value) PLATFORM
	{
		if (Visible == Value)
			return true;

		// Cursor is visible only if display count >= 0

		if (Value) // Show
		{
			int Result = -1;
			while (Result < 0)
			{
				Result = ShowCursor(true);
			}
		}
		else // Hide
		{
			int Result = 1;
			while (Result >= 0)
			{
				Result = ShowCursor(false);
			}
		}

		Visible = Value;

		return true;
	}

	bool GCursor::SetPosition(GInt32 PosX, GInt32 PosY) PLATFORM
	{
		BOOL Result = ::SetCursorPos(PosX, PosY);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		return true;
	}

	bool GCursor::GetPosition(GInt32& PosX, GInt32& PosY) PLATFORM
	{
		POINT CursorPos;
	
		BOOL Result = GetCursorPos(&CursorPos);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		PosX = CursorPos.x;
		PosY = CursorPos.y;

		return true;
	}

	GWindow* GCursor::CollisionCheck()  PLATFORM
	{
		GUtil::GError::Error("Not implemented yet.");

		return NULL;
	}

	bool GCursor::SetLockWindow(GWindow* Window) PLATFORM
	{
		if (Window == NULL)
		{
			BOOL Result = ClipCursor(NULL);
			if (!Result)
			{
				GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
				return false;
			}

			return true;
		}

		GInt32 PosX, PosY;
		Window->GetPosition(PosX, PosY);

		GInt32 Width, Height;
		Window->GetSize(Width, Height);

		RECT ScreenRect = {0};
		ScreenRect.left = PosX;
		ScreenRect.top = PosY;
		ScreenRect.right = PosX + Width;
		ScreenRect.bottom = PosY + Height;

		/*
		POINT Point;
		RECT Rect, ScreenRect;
	
		GetClientRect((HWND)Window->GetHandle(), &Rect);
		Point.x = Rect.left; 
		Point.y = Rect.top;
	
		ClientToScreen((HWND)Window->GetHandle(), &Point);
		ScreenRect.left = Point.x; 
		ScreenRect.top = Point.y;

		Point.x = Rect.right; 
		Point.y = Rect.bottom;
	
		ClientToScreen((HWND)Window->GetHandle(), &Point);
		ScreenRect.right = Point.x; 
		ScreenRect.bottom = Point.y;
		*/

		BOOL Result = ClipCursor(&ScreenRect);
		if (!Result)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		LockWindow = Window;
		return true;
	}

}